import { Injectable, Inject } from "@angular/core";
import { Router } from "@angular/router";
import { Actions, Effect, ofType } from "@ngrx/effects";
import { of } from "rxjs";
import { catchError, exhaustMap, tap, combineLatest } from "rxjs/operators";
import {
  ISelectSymbolResponse,
  ISelectSymbolRequest,
  IMu,
  IZi,
  IAddOrderRequest,
  IDelOrderRequest,
  ISelectOrderRequest,
  ISelectCoinListsRequest
} from "@/main/store/models/main";

import { Store, select } from "@ngrx/store";
import * as fromMain from "@/main/store/reducers/index";
import * as fromRoot from "@/reducers/index";
import { map, filter, skip, switchMap } from "rxjs/operators";
import { Subscription } from "rxjs";
import { UserActions } from "@/user/store/actions";
import { combineAll, debounceTime } from "rxjs/operators";
import { MainActions } from "@/main/store/actions";

import * as fromUser from "@/user/store/reducers/index";
import { ActivatedRoute } from "@angular/router";

@Injectable()
export class MainEffects {
  user$ = this.store.pipe(
    select(fromRoot.user),
    filter(user => !!user)
  );

  query: any;

  user: any;

  constructor(
    private actions$: Actions,
    @Inject("SymbolService") private symbolService,
    @Inject("MsgService") private msgService,
    @Inject("UserService") private userService,
    private router: Router,
    private store: Store<fromMain.State | fromUser.State | fromRoot.State>,
    private activeRouter: ActivatedRoute
  ) {
    this.activeRouter.queryParams.subscribe(e => {
      this.query = e;
    });
    this.user$.subscribe(e => {
      this.user = e;
    });
  }

  @Effect()
  selectSymbol$ = this.actions$.pipe(
    ofType<MainActions.SelectSymbol>(MainActions.MainActionTypes.SelectSymbol),
    map(action => action.payload.req),
    exhaustMap((req: ISelectSymbolRequest) => {
      return this.symbolService.select(req).pipe(
        map((res: any) => {
          return new MainActions.SelectSymbolSuccess({ res });
        }),
        catchError(error => of(new MainActions.SelectSymbolError({ error })))
      );
    })
  );

  @Effect({ dispatch: false })
  selectSymbolSuccess$ = this.actions$.pipe(
    ofType(MainActions.MainActionTypes.SelectSymbolSuccess),
    tap((response: any) => {
      const { payload } = response;
      // if (200 === payload.res.code) {
      //   this.msgService.success("success");
      // } else {
      //   this.msgService.error("error");
      // }
    })
  );

  @Effect({ dispatch: false })
  selectSymbolError$ = this.actions$.pipe(
    ofType(MainActions.MainActionTypes.SelectSymbolError),
    tap(() => {
      this.msgService.error("error");
    })
  );
}
